Component({
  data: {
    topicModules: [],
    hasMore: true,
    currentModuleId: '',
    currentModuleTopics: []
  },
  properties: {
    topic: {
      type: Object,
      observer: '__topicObserver',
      value: null
    },
    search: {
      type: String
    }
  },
  created() {
    const global = getApp().globalData
    this.wxApi = global.wxApi;
    this.topicAPI = global.topicApi;
    this.pageSize = 10;
    this.pageNo = 1;
  },
  methods: {
    __topicObserver(val) {
      console.log('搜索到的知识点')
      this.setData({
        topicModules: []
      })
      this.setData({
        currentModuleId: ''
      })
      this.packTopicData(val);
    },
    packTopicData(val) {
      console.log(val);
      if (!val || JSON.stringify(val) == '{}') return null;
      let topicModules = [];
      const topicTypes = ['biology', 'chemistry', 'chinese', 'english', 'geography', 'history', 'math', 'physics', 'politics']
      let topicNum = 0;

      topicTypes.forEach(type => {
        let topicModule = val[type + 'Topics'];
        let topicLen = topicModule.records.length;
        let obj = {}
        if (topicLen) {
          obj.subjectName = topicModule.records[0].subjectName;
          obj.subjectId = topicModule.records[0].subjectId;
          obj.topics = topicModule.records;
          obj.total = topicModule.total;
          obj.pageSize = topicModule.pageSize;
          topicModules.push(obj);
        }
      });
      this.setData({
        topicModules: topicModules
      })
      console.log(topicModules);
    },
    onTopicDetail(e) {
      let params = {
        topic: this.wxApi.encodeURI(e.detail)
      }
      this.wxApi.navigateTo('../topic-detail/topic-detail', params)
    },
    onTopicsMore(e) {
      let topicModule = e.currentTarget.dataset.topic;
      this.setData({
        currentModuleId: topicModule.subjectId
      })
      let params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        subjectId: topicModule.subjectId,
        fuzzyTopicName: this.data.search
      }
      this.topicAPI.searchTopics(params, (res, code) => {
        let topics = res.records;
        if (topics.length) {
          let totalTopics = this.data.currentModuleTopics;
          totalTopics = totalTopics.concat(res.records);
          this.pageNo ++;
          this.setData({
            currentModuleTopics: totalTopics
          })
          if (topics.length < this.pageSize) {
            this.setData({
              hasMore: false
            })
          } else {
            this.setData({
              hasMore: true
            })
          }
        } else {
          this.setData({
            hasMore: false
          })
        } 
      })
    }
  },

})